<?php
$args = $_GET;
$openid = isset($args['openid'])?$args['openid']:'';
if(!$openid) die('page error');
$openid = UtilHelper::safe_sqlstr($openid);

$wxconf = C('USER_WXCONFIG');
$wechat = new Wechat($wxconf);
//print_r(C('USER_WXCONFIG'));
$js_ticket = $wechat->getJsTicket();
if (!$js_ticket) {
	echo "获取js_ticket失败！<br>";
    echo '错误码：'.$wechat->errCode;
    echo ' 错误原因：'.ErrCode::getErrText($wechat->errCode);
    exit;
}
$timestamp = time();
$noncestr = $wechat->generateNonceStr();
$url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

$cardService = loadService('Card');
// 随机获取card
$cardid = $cardService->logicGetCardidByOpenid($openid);
//$cardid = 'pNPWOuIU-lemtzgG0Z3gtxzKTrE4';
if($cardid===0) {
    die('error openid');
}
if($cardid===2) {
    die('没有卡券了');
}

// 坑死，wechat的签名方法不行！！！
function getCardSign($timestamp,$cticket,$nonce_str,$card_id){
    $card = array(
        $timestamp,
        $cticket,
        $card_id,
        $nonce_str
    );
    $return = '';
    sort($card,SORT_STRING);
    foreach($card as $k=>$v){
        $return .= $v;
    }
    return sha1($return);
}
$tsign = array();
$apiticket = $wechat->getJsCardTicket();
$noncestr = '';
$cardsign = getCardSign($timestamp, $apiticket, $noncestr, $cardid);
$tsign = array(
    'timestamp' => $timestamp,
    'cardSign' => $cardsign
);

C('jsticket', $js_ticket);
C('cardid', $cardid);
C('openid', $openid);
C('jssign', $wechat->getJsSign($url, $timestamp, $noncestr)); //会自己检测调用checkAuth方法获取access_token
//$tsign = $wechat->getCardSign('GIFT', $cardid);
C('cardsign', $tsign);

//echo $js_ticket;
//echo $cardid;
//echo "<hr>";
//print_r(C('jssign'));
//exit;
loadView();
?>
